package main


import (
	"fmt"
	"time"
	"math/rand"
)

func generator2() chan int{
	out := make(chan int)

	go func() {
		i := 0
		for j := 0; j< 3;j++ {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()

	return out
}

// 接收channel
func worker2(id int, c chan int)  {
	for n := range c{
		fmt.Println("worker:" , n)
	}
}

// 返回发送的channel
func createWorker2(n int) chan<- int{
	c := make(chan int)
	go worker2(n, c)
	return c
}

func main()  {

	var c1, c2 = generator2(), generator2()  // 返回channel

	// 接收类型的chanel
	w := createWorker2(0)

	n := 0 // 定义变量0
	hasValue := false // 定义变量false

	for  {
		var a chan<- int  // 初始化一个nil 的 channel

		if hasValue { // 如果这个变量为true，讲接收类型chan为 w 赋值给 a 的chan
			a = w // 实例化chan
			//fmt.Println(w)
		}

		select {
		case n = <- c1:
			hasValue = true
		case n = <- c2:
			hasValue = true
		case a <- n:
			fmt.Println("nnnnnnnnnnn", n)
			hasValue = false
		}
	}
}
